package com.kang.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.alibaba.fastjson.JSON;
import com.kang.pojo.AjaxResult;
import com.kang.pojo.ReturnOrder;
import com.kang.pojo.ReturnRequestItem;
import com.kang.service.AssistService;
import com.kang.service.CategoryService;
import com.kang.service.ReturnOrderService;
import com.kang.service.SupplierService;
import com.kang.service.WarehouseService;
import com.kang.until.ReturnAgentExcelExport;
import com.kang.until.StoragePDF;
import com.vonechina.entity.page.PurchaseAgentPage;
import com.vonechina.entity.page.ReturnAgentPage;
import com.vonechina.entity.page.ReturnRequestItemPage;

/**
 * 待退货物资控制层
 * 
 * @author zs614
 *
 */
@Controller
@RequestMapping("returnAgent")
@SessionAttributes({ "returnAgentPage" })
public class ReturnAgentController extends com.kang.controller.Controller {
	/**
	 * 退货订单服务层
	 */
	@Resource
	private ReturnOrderService returnOrderService;
	/**
	 * 采购分类服务层
	 */
	@Resource
	private CategoryService categoryService;
	/**
	 * 仓库服务层
	 */
	@Resource
	private WarehouseService warehouseService;
	/**
	 * 通用服务层
	 */
	@Resource
	private AssistService assistService;
	/**
	 * 供应商服务层
	 */
	@Resource
	private SupplierService supplierService;

	/**
	 * 分页查看待退货物资界面
	 * 
	 * @param session
	 * @param model
	 * @param returnAgentPage
	 *            搜索条件自动封装实体类
	 * @return 返回jsp页面
	 */
	@RequestMapping("listReturnAgent")
	public String listReturnAgent(HttpSession session, Model model, ReturnAgentPage returnAgentPage) {
		initRight(session);
		if (checkRight("查看待退货物资") != SUCCESS) {
			return "basic/noRight";
		}		
		model.addAttribute("organizations", assistService.listOrganization());
		model.addAttribute("cruiseList", assistService.listCruise());
		model.addAttribute("itemList", returnOrderService.listReturnRequestItem(returnAgentPage));
		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());
		model.addAttribute("categoryList", categoryService.listAllCategory());
		returnAgentPage.setPageUrl("returnAgent/listReturnAgent.do");
		model.addAttribute("page", returnAgentPage);
		model.addAttribute("isAddReturnOrder", checkRight("新增退货单") == SUCCESS);
		return "stockout/returnAgent/listReturnAgent";
	}

	/**
	 * 前往退货订单界面
	 * 
	 * @param session
	 * @param model
	 * @param returnAgentPage
	 * @return 返回jsp页面
	 */
	@RequestMapping("toAddReturnOrder")
	public String toAddReturnOrder(HttpSession session, Model model, PurchaseAgentPage returnAgentPage) {
		initRight(session);
		if (checkRight("新增退货单") != SUCCESS) {
			return "basic/noRight";
		}
		model.addAttribute("supplierList", supplierService.listAllSupplier());
		model.addAttribute("cruiseList", assistService.listCruise());
		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());
		return "stockout/returnAgent/addReturnOrder";
	}

	/**
	 * 新增退货订单
	 * 
	 * @param session
	 * @param order
	 *            退货订单实体类自动封装
	 * @param itemIds
	 *            退货订单物品来源ID
	 * @return 返回json字符串
	 */
	@RequestMapping("addReturnOrder")
	@ResponseBody
	public String addReturnOrder(HttpSession session, ReturnOrder order, Integer[] itemIds) {
		AjaxResult result = new AjaxResult();
		initRight(session);
		if (checkRight("新增退货单") != SUCCESS) {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		order.setCreatePersonID((Integer) session.getAttribute("userID"));
		order.setLastModifiedID((Integer) session.getAttribute("userID"));
		int a = returnOrderService.addReturnOrder(order);
		if (a > 0) {
			returnOrderService.saveReturnOrderItem(order, itemIds);
			result.setResult("success");
			if (order.getStatus() != null && order.getStatus() == 1) {
				order.setSubmitterID((Integer) session.getAttribute("userID"));
				returnOrderService.submitReturnOrder(order);
			}
		}
		return JSON.toJSONString(result);
	}

	/**
	 * 新增退货订单查询可用物品
	 * 
	 * @param page
	 *            搜索条件自动封装
	 * @return 返回json字符串
	 */
	@RequestMapping("listItemNotIn")
	@ResponseBody
	public String listItemNotIn(ReturnRequestItemPage page) {
		AjaxResult result = new AjaxResult();
		result.setRows(returnOrderService.listReturnRequestItemNotIn(page));
		result.setTotal(page.getRows());
		return JSON.toJSONString(result);
	}
	
	
	/**
	 * 导出待退货物资PDF文件
	 * 
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("downloads")
	public void downloadPDF(HttpServletResponse response, ReturnAgentPage returnAgentPage)
			throws Exception {
		//GeneralStorage gStorage = pService.selectoneid(warehousenumber);
		//List<Picking> pkList = pService.listPicking(page);// 查询采购入库数据集合

		List<ReturnRequestItem> rriList = returnOrderService.listReturnRequestItem(returnAgentPage);

		System.out.println("======PickingPage========"+returnAgentPage);
		//此方法为直接下载文件
		//File file = WarehouseOrderPDF.buildWarehouseOrderPDF(warehouseOrder, pOrderItem);
		File file = StoragePDF.ReturnAgentPDF(rriList);
		if (file.isFile() && file.exists()) {
			try {
				 InputStream fis = new BufferedInputStream(new FileInputStream(file));
				    byte[] buffer = new byte[fis.available()];
				    fis.read(buffer);
				    fis.close();
				    response.reset();
				    //乱码处理
				    //先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
				    response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
				    response.addHeader("Content-Length", "" + file.length());
				    OutputStream os = new BufferedOutputStream(response.getOutputStream());
				    response.setContentType("application/octet-stream");
				    os.write(buffer);//输出文件
				    os.flush();
				    os.close();//关闭流，释放资源！
			} catch (Exception e) {
				e.printStackTrace();
			}
			file.delete();
		}
	}
	
	
	/**
	 * 导出待退货物资Excel文件
	 * @param 
	 * @throws
	 */
	@RequestMapping("downloadExcel")
	public void downloadPurchaseAgentExcel(HttpServletRequest request, HttpServletResponse response, ReturnAgentPage returnAgentPage) 
			throws Exception {
//		System.out.println("======待采购Excel=======");
		
		List<ReturnRequestItem> rriList = returnOrderService.listReturnRequestItem(returnAgentPage);
		
		//此方法为直接下载文件
		File file = ReturnAgentExcelExport.buildReturnAgentExcel(request, response, rriList);
		if (file.isFile() && file.exists()) {
			try {
				 InputStream fis = new BufferedInputStream(new FileInputStream(file));
				    byte[] buffer = new byte[fis.available()];
				    fis.read(buffer);
				    response.reset();
				    //乱码处理
				    //先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
				    response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
				    response.addHeader("Content-Length", "" + file.length());
				    OutputStream os = new BufferedOutputStream(response.getOutputStream());
				    response.setContentType("application/octet-stream");
				    os.write(buffer);//输出文件
				    os.flush();
				    os.close();//关闭流，释放资源！
				    fis.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			file.delete();
		}
		
	}

}
